package com.example.farmer.Adapter;

import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.farmer.R;

import java.util.List;

public class ImageSelectionAdapter extends RecyclerView.Adapter<ImageSelectionAdapter.ViewHolder> {

    public List<Uri> mImageUris;

    // 构造函数
    public ImageSelectionAdapter(List<Uri> imageUris) {
        mImageUris = imageUris;
    }

    // 设置新的图片列表并通知数据集改变
    public void setItems(List<Uri> imageUris) {
        this.mImageUris = imageUris;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Uri imageUri = mImageUris.get(position); // 获取当前位置的图片 Uri
        Glide.with(holder.itemView.getContext()).load(imageUri).into(holder.imageView); // 使用 Glide 加载图片

        // 为删除按钮设置点击事件
        holder.deleteButton.setOnClickListener(v -> {
            // 删除图片
            mImageUris.remove(position);
            notifyItemRemoved(position);
            Toast.makeText(holder.itemView.getContext(), "图片已删除", Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public int getItemCount() {
        return mImageUris != null ? mImageUris.size() : 0;
    }

    // ViewHolder 类
    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView deleteButton;

        ViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            deleteButton = itemView.findViewById(R.id.deleteButton);

            // 设置删除按钮的点击事件
            deleteButton.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    mImageUris.remove(position);
                    notifyItemRemoved(position);
                }
            });

        }
    }
}
